define([
	"UtilDir/util",
	"UtilDir/tool",
    "UtilDir/org/selectOrg",
    "UtilDir/searchBlock",
	"static/app/hddc/hddccjcommon/hddccjprojectmethod",
	"Date","DateCN", "css!DateCss",
	"EasyUI","EasyUI-lang"
    ],function(Util, Tool, SelectOrg, SearchBlock,hddccjprojectmethod){

    var sysPath =  getServer() + "/static/app/hddc/hddccjproject";

    var hddcCjProjectFormHtml = sysPath + "/views/hddcCjProjectForm.html";
	var getHddcCjProjectController = function(){
		return getServer() + "/hddc/hddcCjProjects";
	};

	/**
	 * 页面初始化
	 */
	var init = function(){
        initSearchBlock();
        queryBtnBind();
		//initProvinceSelect();
		//initCitySelect();
		//initAreaSelect();
		initcreateProvince();
		createHddcCjProjectGrid();
	};
	var initProvinceSelect = function () {
		$.ajax({
			url: getHddcCjProjectController() + "/getValidDictItemsByDictCode/" + "",
			type: "get",
			success: function (data) {
				var mySelect = document.getElementById("provinceSelect");
				mySelect.add(new Option("请选择", ''), 0);
				for (var i = 0; i < data.length; i++) {
					var name = data[i].dictItemName;
					var code = data[i].dictItemCode;
					mySelect.add(new Option(name, code));
				}
			}
		});
	};
	var initCitySelect = function () {
		$.ajax({
			url: getHddcCjProjectController() + "/getValidDictItemsByDictCode/" + "",
			type: "get",
			success: function (data) {
				var mySelect = document.getElementById("citySelect");
				mySelect.add(new Option("请选择", ''), 0);
				for (var i = 0; i < data.length; i++) {
					var name = data[i].dictItemName;
					var code = data[i].dictItemCode;
					mySelect.add(new Option(name, code));
				}
			}
		});
	};
	var initAreaSelect = function () {
		$.ajax({
			url: getHddcCjProjectController() + "/getValidDictItemsByDictCode/" + "",
			type: "get",
			success: function (data) {
				var mySelect = document.getElementById("areaSelect");
				mySelect.add(new Option("请选择", ''), 0);
				for (var i = 0; i < data.length; i++) {
					var name = data[i].dictItemName;
					var code = data[i].dictItemCode;
					mySelect.add(new Option(name, code));
				}
			}
		});
	};

		var initProvinceSelectFrom = function () {
		$.ajax({
			url: getHddcCjProjectController() + "/getValidDictItemsByDictCode/" + "",
			type: "get",
			success: function (data) {
				var mySelect = document.getElementById("province");
				mySelect.add(new Option("请选择", ''), 0);
				for (var i = 0; i < data.length; i++) {
					var name = data[i].dictItemName;
					var code = data[i].dictItemCode;
					mySelect.add(new Option(name, code));
				}
			}
		});
	};
		var initCitySelectFrom = function () {
		$.ajax({
			url: getHddcCjProjectController() + "/getValidDictItemsByDictCode/" + "",
			type: "get",
			success: function (data) {
				var mySelect = document.getElementById("city");
				mySelect.add(new Option("请选择", ''), 0);
				for (var i = 0; i < data.length; i++) {
					var name = data[i].dictItemName;
					var code = data[i].dictItemCode;
					mySelect.add(new Option(name, code));
				}
			}
		});
	};
		var initAreaSelectFrom = function () {
		$.ajax({
			url: getHddcCjProjectController() + "/getValidDictItemsByDictCode/" + "",
			type: "get",
			success: function (data) {
				var mySelect = document.getElementById("area");
				mySelect.add(new Option("请选择", ''), 0);
				for (var i = 0; i < data.length; i++) {
					var name = data[i].dictItemName;
					var code = data[i].dictItemCode;
					mySelect.add(new Option(name, code));
				}
			}
		});
	};
		var createPersonIdsUserSelectFrom = function () {
			SelectOrg.init({
				id: "personIdsName",
				multi: false,
				title: "请选择用户",
				hideTag: true,
				tagType: ["user"],
				callback: function (data) {
					if (data.user.length == 0){
						Util.alert("请选择用户");
						return;
					}
					$("#personIds").val(data.user[0].userId);
					$("#personIdsName").val(data.user[0].userName);
				}
			});
		};

	var initSearchBlock = function(){
        SearchBlock.init("searchBlock");
	};
	var queryBtnBind = function(){
        $("#btnSearch").click(function () {
            createHddcCjProjectGrid();
        });
        $("#btnReset").click(function () {
            $("#provinceSelect").val("");$("#qualityinspectionStatusSelect").val("");
	            $("#citySelect").val("");
	            $("#areaSelect").val("");
				$("#projectNameCondition").val("");
			});
	};
	var createHddcCjProjectGrid= function() {
        $("#hddcCjProjectGrid").datagrid({
            url:getHddcCjProjectController() + "/queryHddcCjProjects",
			//url:getHddcCjProjectController() + "/queryHddcCjProjectsByPersonId/"+"531ec1e7509c4e07b21bb36d254f3ea6",
			method:"GET",
            fitColumns: true,
            autoRowHeight: false,
            columns:[[
				{field:"ck",checkbox:true},
				{
					field:'province',sortable:true,
					title:'省',
					width:'20%',
					align:'center',
				},
				{
					field:'city',sortable:true,
					title:'市',
					width:'20%',
					align:'center',
				},
				{
					field:'area',sortable:true,
					title:'区（县）',
					width:'20%',
					align:'center',
				},
				{
					field:'projectId',
					title:'项目ID',
					width:'20%',
					align:'center',
				},
				{
					field:'projectName',
					title:'项目名称',
					width:'20%',
					align:'center',
					formatter:function(value,rowData,rowIndex){
						return '<a href="#" onclick="_editHddcCjProject(\'' + rowData.id + '\');"> '+rowData.projectName+' </a> '
					}
				},
				{
					field:'personIds',
					title:'人员信息',
					width:'20%',
					align:'center',
				},
				{
					field:'projectInfo',
					title:'项目描述',
					width:'20%',
					align:'center',
				},
                {
                    field:'createUser',
                    title:'上传人',
                    width:'20%',
                    align:'center'
                },
                {
                    field:'updateTime',
                    title:'上传时间',
                    width:'20%',
                    align:'center',
                },
            ]],
            toolbar: [{
                iconCls: 'fa fa-plus-circle',
                text:"添加",
                handler: function(){
                    addHddcCjProject();
                }
            },{
                iconCls: 'fa fa-trash-o',
                text:"删除",
                handler: function(){
                    deleteHddcCjProject();
                }
            }],
            queryParams:{
                province: $("#provinceSelect").val(),
                city: $("#citySelect").val(),
                area: $("#areaSelect").val(),
				projectName: $("#projectNameCondition").val(),
            },
            pagination: true,
            pageSize: 10
        });
    };
	var formValidator = function(){
		$("#hddcCjProjectForm").validate({
			rules : {
				projectId : {
					required : true,
				},
				projectName : {
					required : true,
				},
				personIds : {
					required : true,
				},
			},
			messages : {
				projectId : {
					required : "项目ID不允许为空!",
				},
				projectName : {
					required : "项目名称不允许为空!",
				},
				personIds : {
					required : "人员信息不允许为空!",
				},
			}
		});
	};
	var getHddcCjProject = function(id){
		$.ajax({
			url: getHddcCjProjectController() + "/"+id,
			type: "get",
			success: function (data) {
				editProvince(data.province, data.city, data.area);
				Tool.deserialize("hddcCjProjectForm", data);
			}
		});
	};
/*
	var projectdatas = null;
	var initcreateProject = function () {
		$.ajax({
			url:getHddcCjProjectController() + "/queryAllHddcCjProjects",
			type: "get",
			success: function (data) {
				projectdatas = data;
			}
		});

	}
 */

	var addHddcCjProject = function () {
		var slidebar = Util.slidebar({
			url: hddcCjProjectFormHtml,
			width: "800px",
			cache: false,
			close : true,
			afterLoad: function () {
				//initProvinceSelectFrom();
				//initCitySelectFrom();
				//initAreaSelectFrom();
				document.getElementById("projectName").readOnly=false;
				document.getElementById("projectId").readOnly=false;
				initcreateProvinceForm();
				createPersonIdsUserSelectFrom();
				formValidator();
				debugger;
				$("#saveBtn").on("click", function () {
					var projectdatas = hddccjprojectmethod.getAllProject();
					var projectName=$("#projectName").val();
					var projectId=$("#projectId").val();
					for(var i =0;i<projectdatas.length;i++){
						if(projectdatas[i].projectId==projectId){
							alert("项目ID不能重复");
							return;
						}
						if(projectdatas[i].projectName==projectName){
							alert("项目名称不能重复");
							return;
						}
					}

					if($("#hddcCjProjectForm").valid()){
						var data = Tool.serialize("hddcCjProjectForm");
						$.ajax({
							url: getHddcCjProjectController() ,
                            contentType:"application/json",
							data: JSON.stringify(data),
							type: "post",
							success: function (data) {
								Util.alert(data.message);
								slidebar.close();
                                createHddcCjProjectGrid();
							}
						});
					}
				});
			}
		});
	};
	window._editHddcCjProject = function(hddcCjProjectId) {
		debugger;
		var slidebar = Util.slidebar({
			url: hddcCjProjectFormHtml,
			width: "800px",
			cache: false,
			close : true,
			afterLoad: function () {
				//initProvinceSelectFrom();
				//initCitySelectFrom();
				//initAreaSelectFrom();
				debugger;
				//$("#projectName").setReadOnly(true);
				//$("#projectId").setReadOnly(false);
				document.getElementById("projectName").readOnly=true;
				document.getElementById("projectId").readOnly=true;
				createPersonIdsUserSelectFrom();
				formValidator();
				getHddcCjProject(hddcCjProjectId);
				$("#saveBtn").on("click", function () {
					var projectdatas = hddccjprojectmethod.getAllProject();
					var projectName=$("#projectName").val();
					var projectId=$("#projectId").val();
					for(var i =0;i<projectdatas.length;i++){
						if(projectdatas[i].projectId==projectId){
							continue;
						}
						if(projectdatas[i].projectName==projectName){
							alert("项目名称不能重复");
							return;
						}
					}
					if($("#hddcCjProjectForm").valid()){
						var data = Tool.serialize("hddcCjProjectForm");
						$.ajax({
							url: getHddcCjProjectController(),
                            contentType:"application/json",
                            data: JSON.stringify(data),
							type: "post",
							success: function (data) {
								Util.alert(data.message);
								slidebar.close();
								createHddcCjProjectGrid();
							}
						});
					}
				});
			}
		});
	};
	var deleteHddcCjProject = function() {
		var rows = $("#hddcCjProjectGrid").datagrid("getSelections");
		if (rows == null || rows.length == 0) {
			Util.alert("请选择一行数据!");
			return;
		}
		Util.confirm("是否要删除选中的数据?", function() {
			var ids = "";
			$.each(rows, function(i, row){
				ids += row.uuid + ",";

			});
			ids = ids.substr(0,ids.length - 1);
			$.ajax({
				url: getHddcCjProjectController() ,
				data: {
					ids : ids
				},
				type: "post",
				success: function (data) {
					createHddcCjProjectGrid();
				}
			});
		}, function() {
			return;
		});

	};

	var initcreateProvince = function () {
		var html = "";
		$("#citySelect").append(html);
		$("#areaSelect").append(html);
		$.ajax({
			url: getServer() + "/divisions/root/subdivisions",
			contentType: "application/json",
			type: "get",
			success: function (data) {
				$.each(data, function (idx, item) {
					html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
				});
				$("#provinceSelect").append(html);
			}
		});
		$("#provinceSelect").change(function () {
			var html = '<option value="" disabled selected style="display:none;">请选择</option>';
			$("#citySelect option").remove();
			$("#citySelect").append(html);
			$("#areaSelect option").remove();
			$("#areaSelect").append(html);
			var divisionId = $(this).find("option:selected").attr("exid");
			if ($(this).val() == "北京市" || $(this).val() == "天津市" || $(this).val() == "上海市" || $(this).val() == "重庆市") {
				$("#citySelect").append("<option value='" + $(this).val() + "' exid='" + divisionId + "'>" + $(this).val() + "</option>");
				return;
			}
			$.ajax({
				url: getServer() + "/divisions/" + divisionId + "/subdivisions",
				contentType: "application/json",
				type: "get",
				success: function (data) {
					$.each(data, function (idx, item) {
						html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
					});
					$("#citySelect").append(html);
				}
			});
		});
		$("#citySelect").change(function () {
			if ($(this).val() == "") return;
			var html = '<option value="" disabled selected style="display:none;">请选择</option>';
			$("#areaSelect option").remove();
			$("#areaSelect").append(html);
			var divisionId = $(this).find("option:selected").attr("exid");
			$.ajax({
				url: getServer() + "/divisions/" + divisionId + "/subdivisions",
				contentType: "application/json",
				type: "get",
				success: function (data) {
					$.each(data, function (idx, item) {
						html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
					});
					$("#areaSelect").append(html);
				}
			});
		});
	}
	var initcreateProvinceForm = function () {
		var html = "";
		$("#city").append(html);
		$("#area").append(html);
		$.ajax({
			url: getServer() + "/divisions/root/subdivisions",
			contentType: "application/json",
			type: "get",
			success: function (data) {
				$.each(data, function (idx, item) {
					html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
				});
				$("#province").append(html);
			}
		});
		$("#province").change(function () {
			var html = '<option value="" disabled selected style="display:none;">请选择</option>';
			$("#city option").remove();
			$("#city").append(html);
			$("#area option").remove();
			$("#area").append(html);
			var divisionId = $(this).find("option:selected").attr("exid");
			if ($(this).val() == "北京市" || $(this).val() == "天津市" || $(this).val() == "上海市" || $(this).val() == "重庆市") {
				$("#city").append("<option value='" + $(this).val() + "' exid='" + divisionId + "'>" + $(this).val() + "</option>");
				return;
			}
			$.ajax({
				url: getServer() + "/divisions/" + divisionId + "/subdivisions",
				contentType: "application/json",
				type: "get",
				success: function (data) {
					$.each(data, function (idx, item) {
						html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
					});
					$("#city").append(html);
				}
			});
		});
		$("#city").change(function () {
			if ($(this).val() == "") return;
			var html = '<option value="" disabled selected style="display:none;">请选择</option>';
			$("#area option").remove();
			$("#area").append(html);
			var divisionId = $(this).find("option:selected").attr("exid");
			$.ajax({
				url: getServer() + "/divisions/" + divisionId + "/subdivisions",
				contentType: "application/json",
				type: "get",
				success: function (data) {
					$.each(data, function (idx, item) {
						html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
					});
					$("#area").append(html);
				}
			});
		});
	}

	var editProvince = function (Province, City, Area) {
		debugger;
		var html = "";
		$("#city").append(html);
		$("#area").append(html);
		$.ajax({
			url: getServer() + "/divisions/root/subdivisions",
			contentType: "application/json",
			type: "get",
			success: function (data) {
				$.each(data, function (idx, item) {
					if (item.divisionName == Province) {
						debugger;
						var divisionId = item.divisionId;
						var htmlCity = '';
						if (Province == "北京市" || Province == "天津市" || Province == "上海市" || Province == "重庆市") {
							$("#city").append("<option value='" + Province + "' exid='" + divisionId + "'>" + Province + "</option>");
							$('#city').val(City);
							var htmlArea = '';
							$.ajax({
								url: getServer() + "/divisions/" + divisionId + "/subdivisions",
								contentType: "application/json",
								type: "get",
								success: function (data) {
									$.each(data, function (idx, item) {
										htmlArea += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
									});
									$("#area").append(htmlArea);
									$('#area').val(Area);
								}
							});

						} else {
							$.ajax({
								url: getServer() + "/divisions/" + divisionId + "/subdivisions",
								contentType: "application/json",
								type: "get",
								success: function (data) {
									debugger;
									$.each(data, function (idx, item) {
										if (item.divisionName == City) {
											var divisionId = item.divisionId;
											var htmlArea = '';
											$.ajax({
												url: getServer() + "/divisions/" + divisionId + "/subdivisions",
												contentType: "application/json",
												type: "get",
												success: function (data) {
													$.each(data, function (idx, item) {
														htmlArea += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
													});
													$("#area").append(htmlArea);
													$('#area').val(Area);
												}
											});
										}
										htmlCity += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
									});
									$("#city").append(htmlCity);
									$('#city').val(City);
								}
							});
						}
					}
					html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
				});
				$("#province").append(html);
				$('#province').val(Province);
			}
		});
		$("#province").change(function () {
			var html = '<option value="" disabled selected style="display:none;">请选择</option>';
			$("#city option").remove();
			$("#city").append(html);
			$("#area option").remove();
			$("#area").append(html);
			var divisionId = $(this).find("option:selected").attr("exid");
			if ($(this).val() == "北京市" || $(this).val() == "天津市" || $(this).val() == "上海市" || $(this).val() == "重庆市") {
				$("#city").append("<option value='" + $(this).val() + "' exid='" + divisionId + "'>" + $(this).val() + "</option>");
				return;
			}
			$.ajax({
				url: getServer() + "/divisions/" + divisionId + "/subdivisions",
				contentType: "application/json",
				type: "get",
				success: function (data) {
					$.each(data, function (idx, item) {
						html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
					});
					$("#city").append(html);
				}
			});
		});
		$("#city").change(function () {
			if ($(this).val() == "") return;
			var html = '<option value="" disabled selected style="display:none;">请选择</option>';
			$("#area option").remove();
			$("#area").append(html);
			var divisionId = $(this).find("option:selected").attr("exid");
			$.ajax({
				url: getServer() + "/divisions/" + divisionId + "/subdivisions",
				contentType: "application/json",
				type: "get",
				success: function (data) {
					$.each(data, function (idx, item) {
						html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
					});
					$("#area").append(html);
				}
			});
		});
	}

	return {
		init:init
	};
});
